package com.shelpe.services.algorithm.entity.mongo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

import com.shelpe.services.algorithm.client.SinbadClient;
import com.shelpe.services.algorithm.entity.batis.Keyword;
import com.shelpe.services.algorithm.entity.jpa.Adgroup;
import com.shelpe.services.algorithm.entity.jpa.AutoProductQueue;

import lombok.Data;

@Data
@Document(collection="auto_drive_adjust_logs")
public class AutoDriveActionLog {
	@Id
	private String id;
	@Indexed
	private long adgroupID;
	@Indexed
	private long campaignID;
	@Indexed
	private Date executeTime;
	
	private AutoProductQueue queue;
	private Adgroup adgroup;
	private List<SinbadClient.HandlingKeyword> addKeywords;
	private List<KeywordSnapshot> keywords;
	
	public void addKeyword(Keyword keyword){
		if(this.keywords == null){
			this.keywords = new ArrayList<KeywordSnapshot>();
		}
		KeywordSnapshot ks = new KeywordSnapshot();
		ks.setKeywordID(keyword.getKeywordId());
		ks.setMatchScope(keyword.getMatchscope());
		ks.setWord(keyword.getWord());
		ks.setMaxPrice(keyword.getMaxPrice());
		ks.setIsDefaultPrice(keyword.getIsDefaultPrice()?1:0);
		ks.setMaxMobilePrice(keyword.getMaxMobilePrice());
		ks.setMobileIsDefaultPrice(keyword.getMobileIsDefaultPrice());
		this.keywords.add(ks);
	}
	
	public void from(AutoProductQueue queue, Adgroup adgroup){
		this.queue = queue;
		this.adgroup = adgroup;
		if(adgroup != null){
			this.adgroupID = adgroup.getAdgroupID();
			this.campaignID = adgroup.getCampaignID();
		}
	}
	
	public KeywordSnapshot findByKeywordID(long keywordID){
		
		if(this.keywords != null){
			for(KeywordSnapshot ks: this.keywords){
				if(ks.getKeywordID() == keywordID){
					return ks;
				}
			}
		}
		
		return null;
	}
	
	public void setupID(long adgroupID, Date time){
		this.id = adgroupID + "-" +DateFormatUtils.format(time, "yyyyMMddHHmm");
	}
	
	@Data
	public static class KeywordSnapshot{
		private long keywordID;
		private String word;
		private int matchScope;
		private int maxPrice;
		private int isDefaultPrice;
		private int maxMobilePrice;
		private int mobileIsDefaultPrice;
		
		private int adjustPrice;
		private int newMaxPrice;
		private boolean willBeDeleted;
		
		private boolean result;
	}
}
